package xyz.lwm.lazycat.netpipe.controller;

import xyz.lwm.lazycat.annotation.Inject;
import xyz.lwm.lazycat.netpipe.domain.entity.User;
import xyz.lwm.lazycat.netpipe.service.UserService;
import xyz.lwm.lazycat.utility.Assert;
import xyz.lwm.lazycat.utility.R;
import xyz.lwm.lazycat.utility.StringUtil;
import xyz.lwm.lazycat.web.annocation.Controller;
import xyz.lwm.lazycat.web.annocation.Delete;
import xyz.lwm.lazycat.web.annocation.Get;
import xyz.lwm.lazycat.web.annocation.PathParam;
import xyz.lwm.lazycat.web.annocation.Post;
import xyz.lwm.lazycat.web.annocation.Put;

import java.util.List;

import static xyz.lwm.lazycat.netpipe.util.Constants.ROOT_PATH;

/**
 * 代理配置
 *
 * @author lwm
 */
@Controller(ROOT_PATH)
public class UserController {

    @Inject
    private UserService userService;

    /**
     * 获取用户列表
     */
    @Get("users")
    public R<List<User>> list() {
        return R.ok(userService.list());
    }

    /**
     * 获取用户
     */
    @Get("users/{userId}")
    public R<User> getById(@PathParam("userId") String userId) {
        Assert.isTrue(StringUtil.isNotBlank(userId), "用户ID不可为空");
        return R.ok(userService.getById(userId));
    }

    /**
     * 添加用户
     */
    @Post("users")
    public R<String> save(User user) {
        Assert.isTrue(StringUtil.isNotBlank(user.getUsername()), "用户名不能为空");
        Assert.isTrue(StringUtil.isNotBlank(user.getPassword()), "密码不能为空");
        Assert.isTrue(StringUtil.isNotBlank(user.getNickName()), "昵称不能为空");
        userService.save(user);
        return R.ok("save successfully");
    }

    /**
     * 修改用户
     */
    @Put("users")
    public R<String> update(User user) {
        Assert.isTrue(user.getId() != null, "用户ID不可为空");
        Assert.isTrue(StringUtil.isNotBlank(user.getUsername()), "用户名不能为空");
        Assert.isTrue(StringUtil.isNotBlank(user.getPassword()), "密码不能为空");
        Assert.isTrue(StringUtil.isNotBlank(user.getNickName()), "昵称不能为空");
        userService.updateById(user);
        return R.ok("update successfully");
    }

    /**
     * 删除用户
     */
    @Delete("users/{userId}")
    public R<String> delete(@PathParam("userId") String userId) {
        Assert.isTrue(StringUtil.isNotBlank(userId), "用户ID不可为空");
        userService.removeById(userId);
        return R.ok("delete successfully");
    }

}
